#include "stdafx.h"

#include "gl\glut.h"
#include "tools.h"
#include <cmath>

#define EPTHLON 1e-5

float float_mod(float num, float mod)
{
	int times = (int)(num/mod);
	return num - times*mod;
}


void draw_cylinder(const float* start, const float* end, float radius, int section_direction, bool is_cap)
{
	float start_points[4][3];
	float end_points[4][3];
	int i,j;
	if(section_direction == SECTION_DIRECTION_Y)
	{
		int delta[4][3] = {{1,0,1}, {1,0,-1}, {-1,0,-1}, {-1,0,1}};
		for(i=0; i<4; i++)
		{
			for(j=0; j<3; j++)
			{
				start_points[i][j] = start[j] + radius*delta[i][j];
				end_points[i][j] = end[j] + radius*delta[i][j];
			}
		}
	}
	else if(section_direction == SECTION_DIRECTION_XZ)
	{
		float towards[3] = {end[0]-start[0], end[1]-start[1], end[2]-start[2]};
		float delta[3] = {0.0f,radius,0.0f};
		if(towards[0]*towards[0] > 0.00001f)
		{
			delta[2] = radius / sqrt(1+(towards[2]*towards[2])/(towards[0]*towards[0]));
			delta[0] = - delta[2]*towards[2]/towards[0];
		}
		else
		{
			delta[2] = 0.0;
			delta[0] = radius;
		}
		int delta_i[4][3] = {{1,1,1}, {1,-1,1}, {-1,-1,-1}, {-1,1,-1}};
		for(i=0; i<4; i++)
		{
			for(j=0; j<3; j++)
			{
				start_points[i][j] = start[j] + delta[j]*delta_i[i][j];
				end_points[i][j] = end[j] + delta[j]*delta_i[i][j];
			}
		}

	}

	//draw
	glBegin(GL_TRIANGLE_STRIP);
	for(i=0; i<4; i++)
	{
		glVertex3fv(start_points[i]);
		glVertex3fv(end_points[i]);
	}
	glVertex3fv(start_points[0]);
	glVertex3fv(end_points[0]);
	glEnd();
}

void nomalize(float *vector3d)
{
	float length = sqrt(vector3d[0]*vector3d[0] + vector3d[1]*vector3d[1] + vector3d[2]*vector3d[2]);

	if(length < 0.00001f)
	{
		return;
	}

	vector3d[0] /= length;
	vector3d[1] /= length;
	vector3d[2] /= length;

}

void integer_bresenham_line(int x0,int y0,int x1,int y1, void draw_pixel(int x, int y))
{
	int i,j;
	int x,y,dx,dy,unitx,unity,fabs_dx,fabs_dy,e;
	dx=x1-x0;
	dy=y1-y0;
	fabs_dx = (int)fabs((double)dx);
	fabs_dy = (int)fabs((double)dy);
	
	if(fabs_dx < EPTHLON)
	{
		unitx = 0;
	}
	else
	{
		unitx = dx / fabs_dx ;
	}
	
	if(fabs_dy < EPTHLON)
	{
		unity = 0;
	}
	else
	{
		unity = dy / fabs_dy ;
	}

	x=x0;
	y=y0;
	if( fabs_dx> fabs_dy )
	{
		e=-dx;
		for(i=0;i<=fabs_dx;i++)
		{
			draw_pixel(x,y);
			x+=unitx,e=e+2*dy;
			if(e>=0)
			{
				y+=unity;e=e-2*dx;
			}
		} // for end
	}
	else
	{
		e=-dy;
		for(i=0;i<=fabs_dy;i++)
		{
			draw_pixel(x, y);
			y+=unity,e=e+2*dx;
			if(e>=0)
			{
				x+=unitx;e=e-2*dy;
			}
		} // for end
	}// if end
}